<template>
  <forms ref="forms" :config="config" @submit:forms="onsubmit" :btns="btns">
  </forms>
</template>

<script>
import s94Mjs from "s94-js";
import {iframe} from "@/js/tool.js";
import {ajax} from "@/js/api_tool.js";
import {_config, decode_config} from "@/js/s94_tool.js";

export default {
  props: ['__iframe'],
  data(){
    let id = this.$get('id'), btns = undefined;
    let model_name_config =  decode_config(_config('model_map'), {content_key:'label', value_key:'name'});
    let forms_config = {
      model_name: {label:'项目类型',name:'model_name',type:'select_one',config:model_name_config,tips:''},
      object_ids: {label:'项目ID集',name:'object_ids',type:'list_ids',config:'',tips:'指定特权项目，选定的项目，只有下面符合下面限制的用户才有权查看、购买'},
      user_ids: {label:'限制用户',name:'user_ids',type:'list_ids',config:'/user/index',tips:'限制用户，不选为空表示不限制(即所有用户都有权限)'},
      level: {label:'限制等级',name:'level',type:'checkbox',config:[],tips:'限制等级，不选为空表示不限制(即所有等级都有权限)'},
    }
    if (id){
      forms_config.create_time = {label:'创建时间',name:'create_time',tips:''};
    }
    if (this.$get('is_info')){
      s94Mjs.each(forms_config, function (row){ row.is_info = true; });
      btns = [];
    }
    return {
      id: id,
      btns: btns,
      config: forms_config,
      model_map: {},
    }
  },
  methods: {
    onsubmit(formData){
      let url = this.id ? `/admin/special_object/edit?id=`+this.id : '/admin/special_object/add';
      ajax({url:url, method:'POST', data:formData}, (res)=>{
        if (this.__iframe){
          iframe.exe('special_object/index', '$refs.list_url.list');
          iframe.hide('special_object/edit');
          if (!this.id) this.$refs['forms'].init();
        }else {
          this.$router.push('index');
        }
      }, (res)=>{
        if (res.errors) this.$refs['forms'].errors = res.errors;
      })

    }
  },
  watch: {
    'config.model_name.value'(v, oldV){
      this.config.object_ids.config = `/model_v2_base/index?model_name=${v}`;
    },
  },
  mounted() {
    let app = this;
    if (!this.__iframe) window['app'] = this;
    if (this.id) {
      ajax({url:'/admin/special_object/info?id='+this.id, cache:true}, (res)=>{
        this.$refs['forms'].init(res.data);
        return false;
      }, ()=>{
        if (this.__iframe){
          iframe.remove('special_object/edit');
        }else {
          this.$router.push('index');
        }
      })
    }

    //其他初始化操作
    ajax({url:'/admin/user_level/list', cache:true}, (res)=>{
      this.config.level.config = decode_config(res.data.list, {content_key:'name', value_key:'level'});
      return false
    })
  }
}
</script>
